<template>
  <div>
    <a-breadcrumb>
      <a-breadcrumb-item>
        <router-link to="/home">首页</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>
        <router-link to="/work-ticket/work-ticket">信息查询</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>信息详情</a-breadcrumb-item>
    </a-breadcrumb>
    <a-card>
      <a-form
        ref="formRef"
        :model="formState"
        @finish="onFinish"
        :rules="rules"
      >
        <input type="hidden" v-model="formState.id" name="id"/>
        <h2 style="text-align:center;font-weight: bold;">
          电力通信工作票
          <a-form-item label="请选择场所设备" name="deviceId">
            <a-select
              v-model:value="formState.deviceId"
              style="width: 240px"
              :options="deviceList"
              @change="handleChange"
            >
            </a-select>
          </a-form-item>
        </h2>
        <a-row :gutter="24">
          <a-col :span="15">
            <a-form-item name="unitName">
              <template #label><b style="font-size: 15px;">单位</b></template>
              <a-input v-model:value="formState.unitName" :maxlength="100"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="9">
            <a-form-item name="workTicketCode">
              <template #label><b style="font-size: 15px;">编号</b></template>
              <a-input v-model:value="formState.workTicketCode" :maxlength="100"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="15">
            <a-form-item label="1.班组名称">
              <a-input v-model:value="formState.teamName" :maxlength="100"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="9">
            <a-form-item label="工作负责人" name="workLeader">
              <a-input v-model:value="formState.workLeader" allow-clear :maxlength="100">
                <template #addonAfter>
                  <person-modal @onSelectedPerson="onSelectedPerson"></person-modal>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <div class="zhtt-row">
          2.工作班人员（不包括工作负责人）
          <a-row :gutter="24">
            <a-col :span="19">
              <a-form-item>
                <a-input
                  placeholder="姓名之间请用顿号分开如：李靖、辛弃疾"
                  v-model:value="formState.shiftStaff"
                  @input="inputShiftStaff($event)"
                  allow-clear :maxlength="200">
                  <template #addonAfter>
                    <person-modal :isShowCheckBox="true" @onSelectedPerson="onSelectedShiftStaffPerson"></person-modal>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-input prefix="共" suffix="人" v-model:value="formState.totalNumber"/>
            </a-col>
          </a-row>
        </div>
        <div class="zhtt-row">
          <a-form-item label="3.工作场所名称">
            <a-input v-model:value="formState.workspace" :maxlength="100"></a-input>
          </a-form-item>
        </div>
        <div class="zhtt-row">
          4.工作任务
          <table class="zhtt-table">
            <tr style="text-align: center;">
              <td style="width:40%;">工作地点及设备名称</td>
              <td style="width:60%;">工作内容</td>
            </tr>
            <tr>
              <td>
                <a-input v-model:value="formState.dutyStation" :maxlength="100"></a-input>
              </td>
              <td>
                <a-input v-model:value="formState.jobContent" :maxlength="100"></a-input>
              </td>
            </tr>
          </table>
        </div>
        <div class="zhtt-row">
          5.计划工作时间：
          自<input class="zhtt-input" type="number" v-model="formState.planWorkStartYear" :maxlength="4">年
          <input class="zhtt-input" max="12" @input="planWorkStartMonthInputChange" type="number"  v-model="formState.planWorkStartMonth" :maxlength="2">月
          <input class="zhtt-input" max="31" @input="planWorkStartDateInputChange" type="number" v-model="formState.planWorkStartDate" :maxlength="2">日
          <input class="zhtt-input" max="24" @input="planWorkStartHourInputChange" type="number" v-model="formState.planWorkStartHour" :maxlength="2">时
          <input class="zhtt-input" max="60" @input="planWorkStartMinuteInputChange" type="number" v-model="formState.planWorkStartMinute" :maxlength="2">分
          至<input class="zhtt-input" type="number" v-model="formState.planWorkEndYear" :maxlength="4">年
          <input class="zhtt-input" max="12" @input="planWorkEndMonthInputChange" type="number" v-model="formState.planWorkEndMonth" :maxlength="2">月
          <input class="zhtt-input" max="31" @input="planWorkEndDateInputChange" type="number" v-model="formState.planWorkEndDate" :maxlength="2">日
          <input class="zhtt-input" max="24" @input="planWorkEndHourInputChange" type="number" v-model="formState.planWorkEndHour" :maxlength="2">时
          <input class="zhtt-input" max="60" @input="planWorkEndMinuteInputChange" type="number" v-model="formState.planWorkEndMinute" :maxlength="2">分
        </div>
        <div class="zhtt-row">6.安全措施</div>
        <div class="zhtt-row">
          6.1 电气安全措施：<br/>
          <a-textarea :rows="4" v-model:value="formState.safetyMeasures" show-count :maxlength="255"/>
        </div>
        <div class="zhtt-row">
          6.2通信安全措施（应获得的授权，应验证的内容等，必要时可附页绘图说明）
          <div class="zhtt-row">
            <a-input></a-input>
          </div>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="工作票签发人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-date-picker showTime placeholder="签名时间" format="YYYY-MM-DD HH:mm"/>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="工作负责人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-date-picker showTime placeholder="签名时间" format="YYYY-MM-DD HH:mm"/>
            </a-col>
          </a-row>
        </div>
        <div class="zhtt-row">
          7.现场补充安全措施（工作许可人员填写）
          <div>
            <a-input :maxlength="100"></a-input>
          </div>
        </div>
        <div class="zhtt-row">
          8.工作许可
          <div class="zhtt-row">
            8.1工作许可（电气专业确认1—6.1项的内容，7项中由其补充的内容）：
            <div class="zhtt-row">
              许可开始工作时间：
              <a-date-picker showTime placeholder="许可开始工作时间" format="YYYY-MM-DD HH:mm"/>
            </div>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="工作负责人签名">
                  <a-input :maxlength="100"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="工作许可人签名">
                  <a-input :maxlength="100"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="zhtt-row">
          8.2工作许可（通信专业确认1—5、6.2项的内容，7项中由其补充的内容）：
          <div class="zhtt-row">
            许可开始工作时间：
            <a-date-picker showTime placeholder="许可开始工作时间" format="YYYY-MM-DD HH:mm"/>
          </div>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="工作负责人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="工作许可人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="zhtt-row">
          9.现场交底，工作班成员确认工作负责人布置的工作任务、人员分工、安全措施和注意事项并签名：
          <div class="zhtt-row">
            <a-input :maxlength="100"></a-input>
          </div>
        </div>
        <div class="zhtt-row">
          10.工作票延期
          <div class="zhtt-row">
            <table class="zhtt-table">
              <tr>
                <th>工作延期至</th>
                <th>工作负责人</th>
                <th>通信工作许可人</th>
                <th>电气工作许可人</th>
              </tr>
              <tr>
                <td>
                  <a-date-picker showTime placeholder="工作延期至" format="YYYY-MM-DD HH:mm"/>
                </td>
                <td>
                  <a-input :maxlength="100"></a-input>
                </td>
                <td>
                  <a-input :maxlength="100"></a-input>
                </td>
                <td>
                  <a-input :maxlength="100"></a-input>
                </td>
              </tr>
            </table>
          </div>
        </div>
        <div class="zhtt-row">
          11.工作终结
          <div style="text-indent:2em;">
            全部工作已结束，工作过程中产生的临时数据、临时帐号等内容已删除，电力通信系统运行正常，现场已清扫、整理，布控球已回收，工作班成员已全部撤离工作地点。
          </div>
        </div>
        <div class="zhtt-row">
          11.1 工作终结（通信专业）：
          <div class="zhtt-row">
            工作终结时间：
            <a-date-picker
              showTime
              placeholder="工作终结时间"
              format="YYYY-MM-DD HH:mm"
            />
          </div>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="工作负责人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="工作许可人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="zhtt-row">
          11.2 工作终结（电气专业）：
          <div class="zhtt-row">
            工作终结时间：
            <a-date-picker
              showTime
              placeholder="工作终结时间"
              format="YYYY-MM-DD HH:mm"
            />
          </div>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="工作负责人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="工作许可人签名">
                <a-input :maxlength="100"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="zhtt-row">
          12.备注
          <div>
            <a-form-item label="（1）应设布控球情况">
              <a-input :maxlength="100"></a-input>
            </a-form-item>
          </div>
          <div>
            <a-form-item label="（2）其它事项">
              <a-input :maxlength="100"></a-input>
            </a-form-item>
          </div>
        </div>
      </a-form>
      <div style="height:40px;">
        <div style="width:300px;margin:0 auto;">
          <a-affix :offset-bottom="10">
            <a-button type="primary" size="large" @click="onSubmitUpdate" v-if="formState.createTime">更新</a-button> &nbsp;&nbsp;
            <a-button type="primary" size="large" @click="onSubmit" v-if="!formState.createTime">保存</a-button> &nbsp;&nbsp;
            <a-button style="color:#1890ff" size="large" @click="goback">返回</a-button> &nbsp;&nbsp;
          </a-affix>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRaw, UnwrapRef, ref, onMounted } from 'vue'
import { workTicketType } from './js/work-ticket-dict'
import { WorkTicketModel, formStateValue } from './js/work-ticket-model'
import { WorkTicketApi } from './js/work-ticket-api'
import { message } from 'ant-design-vue'
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { DeviceApi } from '@/views/device/js/device-api'
import { DeviceModel } from '@/views/device/js/device-model'
import { ResultModel } from '@/common/result.model'
import PersonModal from '@/views/biz-common/person-modal.vue'
import { PersonModel } from '@/views/person/js/person-model'

export default defineComponent({
  data () {
    return {
      workTicketType
    }
  },
  mounted () {
    const id: string = this.$route.params.id as string
    if (!id) {
      WorkTicketApi.getWorkTicketyMaxId().then(response => {
        const workTicket: WorkTicketModel = response.data
        if (workTicket && workTicket.workTicketCode) {
          const codeStrs = workTicket.workTicketCode.split('-')
          if (this.formState.workTicketCode && codeStrs[2] === this.formState.workTicketCode.split('-')[2]) {
            let codeStr = ''
            if (codeStrs.length === 4) {
              let codeNum = +codeStrs[3]
              codeStrs[3] = ++codeNum + ''
              let len = 4 - codeStrs[3].length
              while (len-- > 0) {
                codeStr += '0'
              }
              codeStrs[3] = codeStr + codeStrs[3]
              this.formState.workTicketCode = codeStrs.join('-')
            }
          }
        }
      })
    } else {
      WorkTicketApi.getWorkTicketById(id).then(response => {
        const workTicket: WorkTicketModel = response.data
        Object.assign(this.formState, workTicket)
        this.formState.deviceId = workTicket.deviceId
      })
    }
  },
  methods: {
    handleChange (event: string) {
      const device = this.deviceList.find(v => v.value === event)
      if (device) {
        this.formState.workspace = device.workspace
        this.formState.dutyStation = device.label as string
        this.formState.deviceId = device.id as string
        this.formState.teamId = device.teamId as string
        this.formState.safetyMeasures = device.safetyMeasures as string
      }
    },
    goback () {
      this.$router.push('/work-ticket/work-ticket')
    },
    onSelectedPerson (person: PersonModel) {
      this.formState.workLeader = person.name
      this.formRef.validateFields(['workLeader'])
    },
    onSelectedShiftStaffPerson (person: PersonModel | PersonModel[]) {
      if (Array.isArray(person)) {
        const names = person.map(v => v.name)
        this.formState.shiftStaff = names.join('、')
      } else if (person) {
        this.formState.shiftStaff = person.name
      }
      this.inputShiftStaff()
    },
    inputShiftStaff () {
      if (this.formState.shiftStaff) {
        const len = this.formState.shiftStaff.split('、').length
        this.formState.totalNumber = len + ''
      } else {
        this.formState.totalNumber = '0'
      }
    },
    planWorkStartMonthInputChange () {
      const planWorkStartMonth = this.formState.planWorkStartMonth ? this.formState.planWorkStartMonth : '1'
      this.formState.planWorkStartMonth = +planWorkStartMonth > 9 ? planWorkStartMonth : '0' + (+planWorkStartMonth)
      console.log('this.formState.planWorkStartMonth:', this.formState.planWorkStartMonth)
    },
    planWorkStartDateInputChange () {
      const planWorkStartDate = this.formState.planWorkStartDate ? this.formState.planWorkStartDate : '1'
      this.formState.planWorkStartDate = +planWorkStartDate > 9 ? planWorkStartDate : '0' + (+planWorkStartDate)
    },
    planWorkStartHourInputChange () {
      const planWorkStartHour = this.formState.planWorkStartHour ? this.formState.planWorkStartHour : '1'
      this.formState.planWorkStartHour = +planWorkStartHour > 9 ? planWorkStartHour : '0' + (+planWorkStartHour)
    },
    planWorkStartMinuteInputChange () {
      const planWorkStartMinute = this.formState.planWorkStartMinute ? this.formState.planWorkStartMinute : '0'
      this.formState.planWorkStartMinute = +planWorkStartMinute > 9 ? planWorkStartMinute : '0' + (+planWorkStartMinute)
    },
    planWorkEndMonthInputChange () {
      const planWorkEndMonth = this.formState.planWorkEndMonth ? this.formState.planWorkEndMonth : '1'
      this.formState.planWorkEndMonth = +planWorkEndMonth > 9 ? planWorkEndMonth : '0' + (+planWorkEndMonth)
    },
    planWorkEndDateInputChange () {
      const planWorkEndDate = this.formState.planWorkEndDate ? this.formState.planWorkEndDate : '1'
      this.formState.planWorkEndDate = +planWorkEndDate > 9 ? planWorkEndDate : '0' + (+planWorkEndDate)
    },
    planWorkEndHour () {
      const planWorkEndHour = this.formState.planWorkEndHour ? this.formState.planWorkEndHour : '1'
      this.formState.planWorkEndHour = +planWorkEndHour > 9 ? planWorkEndHour : '0' + (+planWorkEndHour)
    },
    planWorkEndHourInputChange () {
      const planWorkEndHour = this.formState.planWorkEndHour ? this.formState.planWorkEndHour : '0'
      this.formState.planWorkEndHour = +planWorkEndHour > 9 ? planWorkEndHour : '0' + (+planWorkEndHour)
    },
    planWorkEndMinuteInputChange () {
      const planWorkEndMinute = this.formState.planWorkEndMinute ? this.formState.planWorkEndMinute : '0'
      this.formState.planWorkEndMinute = +planWorkEndMinute > 9 ? planWorkEndMinute : '0' + (+planWorkEndMinute)
    }
  },
  components: {
    PersonModal
  },
  setup () {
    const defaltFormValue = JSON.parse(JSON.stringify(formStateValue()))
    const formRef = ref()
    const deviceListValue = new Array<DeviceModel>()
    const deviceList = ref(deviceListValue)
    const formState: UnwrapRef<WorkTicketModel> = reactive(defaltFormValue)
    const formValue = toRaw(formState)
    const onSubmit = () => {
      console.log(formValue)
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      formRef.value.validate().then(() => {
        WorkTicketApi.save(formValue).then((response: ResultModel) => {
          message.success('保存成功！')
          console.log(response)
        })
      }).catch((error: ValidateErrorEntity<WorkTicketModel>) => {
        console.log(error)
      })
    }
    onMounted(() => {
      DeviceApi.getDeviceListByTeamId().then((response: ResultModel) => {
        if (Array.isArray(response.data)) {
          response.data.forEach((v: any) => {
            v.value = v.id
            v.label = v.name
          })
        }
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        deviceList.value = response.data
      })
    })
    const onSubmitUpdate = () => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      console.log(formValue.deviceId)
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      formRef.value.validate().then(() => {
        WorkTicketApi.update(formValue).then((response: ResultModel) => {
          message.success('更新成功！')
          console.log(response)
        })
      }).catch((error: ValidateErrorEntity<WorkTicketModel>) => {
        console.log(error)
      })
    }
    const onFinish = () => {
      console.log('onFinish!', JSON.stringify(formValue))
    }
    const rules = {
      workTicketCode: [
        { required: true, message: '编号不能为空！', trigger: 'blur' }
      ],
      workLeader: [
        { required: true, message: '工作负责人不能为空！', trigger: 'blur' }
      ]
    }
    const resetForm = () => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      formRef.value.resetFields()
    }
    return {
      formRef,
      formState,
      resetForm,
      deviceList,
      onSubmit,
      onSubmitUpdate,
      onFinish,
      rules
    }
  },
  beforeUnmount () {
    this.resetForm()
  }
})
</script>
<style scoped lang="less">
@import "work-ticket-form.less";
</style>
